package com.grechur.wanandroidcompose.widget

import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.*


@Composable
fun LazyListState.OnBottomReached(buffer: Int = 0, loadMore: () -> Unit) {
    require(buffer >= 0) {
        "buffer 值必须是正整数"
    }
    //是否应该加载更多的状态
    val shouldLoadMore = remember {
        //因为状态由layoutInfo计算得到
        derivedStateOf {
            //列表为空的话直接返回true
            val lastVisibleItem =
                layoutInfo.visibleItemsInfo.lastOrNull() ?: return@derivedStateOf true
            //如果现实项为最后一个item 返回true
            lastVisibleItem.index == layoutInfo.totalItemsCount - 1 - buffer
        }
    }
    LaunchedEffect(key1 = shouldLoadMore, block = {
        snapshotFlow {
            shouldLoadMore.value
        }.collect {
            if (it) {
                loadMore()
            }
        }
    })
}